/**
 * 关于左侧导航的js脚本程序
 * @author Frank@ADM
 * @date 2013-11-26 11:00:00
 * @version 1.0
 */
function debug(obj) { if (window.console && window.console.log) window.console.log(obj);  };  
(function($){
	var $target = $;
	var $content = null;
	var $title = null;
	var html_loading = '<div class="loading"></div>';
	//核心函数
	$.fn.slider = function(options){
		$target = this;
		var opts = $.extend({}, $.fn.slider.defaults, options);  
		$title = $(opts["target"]+" .tpl-title");
		$content = $(opts["target"]+" .content");
		init(opts);
	};
	//默认的配置信息
	$.fn.slider.defaults = {    
		'target':'#TPL',
		'datatable_config':{
			bJQueryUI: false, bFilter: true,bSort:false,aaSorting:[[0,"desc"]],bLengthChange: false,iDisplayLength:20,
			oLanguage: {sUrl: "js/libs/jquery.datatables/zh.txt" }
		},
		'selector':" a"
	};
	function init(opts){
		$(opts["target"]+" .btn-refresh").die('click');
		$(opts["target"]+" .btn-refresh").live('click',function(){
			var href = $(this).attr("href");
			$.get(href,function(data){
				$content.html(data);
				//$content.find(".datatable").dataTable(opts['datatable_config']);
			});
			return false;
		});
		var selector = opts['selector'];
		$target.find(selector).each(function(){
			$(this).click(function(){
				$title.text($(this).text());
				$content.html(html_loading);
				var $btn_refresh = $title.next(".btn-refresh");
				if($btn_refresh){
					$btn_refresh.attr("href",$(this).attr("href"));
				}
				$.get($(this).attr("href"),function(data){
					$content.html(data);
					//$content.find(".datatable").dataTable(opts['datatable_config']);
				});
				return false;
			});
		});
	}
})(jQuery);

/**
 * 关于工具栏的js脚本程序
 * @author Frank@ADM
 * @date 2013-11-26 11:00:00
 * @version 1.0
 */
/*
(function($){
	var selector = ".toolbar";
	var btnAdd = null,btnEdit = null,btnDel = null,btnSave = null,btnDetail=null;
	//核心函数
	$.fn.toolbar = function(options){
		selector = this.selector;
		var opts = $.extend({}, $.fn.toolbar.defaults, options); 
		init(opts);
	};
	//默认的配置信息
	$.fn.toolbar.defaults = {    
		'btnAdd':'.add',
		'btnEdit':'.edit',
		'btnSave':'.save',
		'btnDel':'.delete',
		'btnDetail':'.detail',
		'target':'FORM-DIALOG'
	};
	function init(opts){
		btnAdd =  $(selector + " " +opts["btnAdd"]);
		btnEdit = $(opts["btnEdit"]);
		btnDel = $(opts["btnDel"]);
		btnSave = $(opts["btnSave"]);
		btnDetail = $(opts["btnDetail"]);
		var $target = $("#"+opts['target']);
		$(".btn-back").live("click",function(){
			$target.modal('hide');
			return false;
		});
		btnDel.live('click',function(){
			var $THIS = $(this);
			bootbox.confirm("确定要删除该条记录么?",function(result){
				if(!result) return;
				$.ajax({dataType:"json",url:$THIS.attr("href")}).done(function(data){
					if(data.code=='0'){
						//删除该行
						$THIS = $THIS.parent().parent();
						$(".datatable").dataTable().fnDeleteRow($THIS.index());
					}else{
						bootbox.alert(data.msg);
					}
				});
			});
			
		});
		
		btnEdit.live('click',function(){
			$.get($(this).attr("href"),function(data){
				$target.html(data).show();
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true  });
			});
			return false;
		});	
		btnAdd.live('click',function(){
			var href = $(this).attr("href");
			//弹窗
			$.get(href,function(data){
				$target.html(data).show();
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true  });
			});
			return false;
		});
		
		btnSave.live('click',function(){
			alert("Test Save Button!");
			return false;
		});
		btnDetail.live('click',function(){
			$.get($(this).attr("href"),function(data){
				//$target.html(data).show();
				bootbox.dialog({message:data,closeButton: true,show:true});
				return false;
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true,closeButton: true });
			});
			return false;
		});
	}
})(jQuery);
//*/
(function($){
	$.arrayToObj = function(arr,option){
		option = $.extend({},{'key':'name','val':'value'}, option);  
		var map = $.map(arr,function(f){
			return f[option.key]+":"+f[option.val];
		});
		var o = {};
		for(var i in arr){
			var row = arr[i];
			o[row[option.key]] = row[option.val];
		}
		return o;
	};
})(jQuery);


(function($){
	var table = null;
	var selector = '.dataTable';
	var btnAdd = null,btnEdit = null,btnDel = null,btnSave = null,btnDetail=null;
	//核心函数
	$.fn.dt = function(options){
		table = this;
		selector = this.selector;
		var opts = $.extend({}, $.fn.dt.defaults, options); 
		init(opts);
	};
	//默认的配置信息
	$.fn.dt.defaults = { 
		'btnAdd':'.add',
		'btnEdit':'.edit',
		'btnSave':'.btn-ajax-save',
		'btnDel':'#btn-delete',
		'btnDetail':'.detail',
		'target':'FORM-DIALOG',
		'fileurl':''
	};
	function init(opts){
		var columnMap = [];
		table.find("th[col]").each(function(){
			columnMap[columnMap.length] = {data:$(this).attr("col")};
		});
		table.find('tbody').on( 'click', 'tr', function () {
	       if ( $(this).hasClass('selected') ) {
	           $(this).removeClass('selected');
	       }
	       else {
	           table.$('tr.selected').removeClass('selected');
	           $(this).addClass('selected');
	       }
	    });
		table = table.DataTable( {
			rowCallback: function( row, data ) {
				if(!data.hasOwnProperty('guid')){ 
					return;
				}
				$("th").each(function(){
					var str = $(this).attr("col");
					if(str.indexOf('_file', str.length - '_file'.length) !== -1){
						var i = $(this).index();
						$(row).find("td").eq(i).html('<a href="'+opts['fileurl']+'/f?guid='+data['guid']+'">'+data[str]+'</a>');
					}
				});
			},
			bJQueryUI: false, bFilter: true,bSort:true,aaSorting:[[0,"desc"]],
			bLengthChange: false,iDisplayLength:20,
			oLanguage: {sUrl: "js/libs/jquery.datatables/zh.txt" },
		       ajax: table.attr("datasource"),
		       columns: columnMap
		   });
		
		
	
		btnAdd =  $(opts["btnAdd"]);
		btnEdit = $(opts["btnEdit"]);
		btnDel = $(opts["btnDel"]);
		btnSave = $(opts["btnSave"]);
		btnDetail = $(opts["btnDetail"]);
		var $target = $("#"+opts['target']);
		$(".btn-back").live("click",function(){
			$target.modal('hide');
			return false;
		});
		
		btnDel.click(function(){
			var id = $(selector+" tbody .selected").attr("id");
			if(id == undefined){
	    		bootbox.alert('您未选择任何条目!');return false;
	    	}
			bootbox.confirm("确定要删除该条记录么?",function(result){
				if(!result) return;
		    	var href = btnDel.attr("href");
		    	
		    	href +=id;
		    	$.get(href,function(rsp){
		    		table.row('.selected').remove().draw( false );
		    	});
		   	});
		});
		
		btnEdit.click(function(){
			var id = $(selector+" tbody .selected").attr("id");
			if(id == undefined){
	    		bootbox.alert('您未选择任何条目!');return false;
	    	}
			var href = $(this).attr("href");
			href+=id;
			$.get(href,function(data){
				$target.html(data).show();
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true  });
			});
			return false;
		});	
		btnAdd.click(function(){
			var href = $(this).attr("href");
			//弹窗
			$.get(href,function(data){
				$target.html(data).show();
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true  });
			});
			return false;
		});
		btnSave.die('click');
		btnSave.live('click',function(){
			var $form = $(this).parents("form");
			var fields = $form.formToArray();
			fields = $.arrayToObj(fields);
			$THIS = $(this);
			var isajax = true;
			
			if("0" == $THIS.attr("isajax")) isajax = false;
			if(!isajax){
				$form.ajaxSubmit({dataType:"html",success:function(html){
					$("#FORM-DIALOG").modal('hide');
						$("#TPL .tpl-title").text(' ');
						$("#TPL .content").html(html);
					}
				});
				return false;
			}
			$form.ajaxSubmit({dataType:"json",success:function(data){
				if(data.code==0){
					var o = $THIS.attr('o');
					if('add'==o){
						var d={};
						d['DT_RowId'] = data.data;
						$(selector + " th").each(function(){
							var col = $(this).attr("col");
							var val = $("form *[name='"+col+"']").val();
							switch($(this).attr("tag")){
							case 'select':
							case 'ynradio':
							case 'hidden':
								var ds = $(this).attr("ds");
								ds = $.parseJSON(ds);
								if(ds.hasOwnProperty(val))
									val = ds[val];
								break;
							case 'file':
								var guid = $("form *[name='guid']").val();
								val = '<a href="'+opts['fileurl']+'/f?guid='+guid+'">'+ val +'</a>';
								break;
							}
							d[col] = val;
						});
						table.row.add(d).draw();
					}else{
						var d={};
						$(selector + " th").each(function(){
							var col = $(this).attr("col");
							var val = $("form *[name='"+col+"']").val();
							switch($(this).attr("tag")){
							case 'select':
							case 'ynradio':
								var ds = $(this).attr("ds");
								ds = $.parseJSON(ds);
								if(ds.hasOwnProperty(val))
									val = ds[val];
								break;
							case 'file':
								var guid = table.row($(selector+" tbody .selected")).data().guid;
								val = '<a href="'+opts['fileurl']+'/f?guid='+guid+'">'+ val +'</a>';
								break;
							}
							d[col] = val;
						});
						table.row($(selector+" tbody .selected")).data(d).draw();
					}
					$("#FORM-DIALOG").modal('hide');
				}else{
					bootbox.alert("<p><i class='icon-remove'></i> "+data.msg+"</p>");
				}
			}});
			return false;
		});
		/*
		$(".btn-ajax-save").live('click',function(){
			var $form = $(this).parents("form");
			var fields = $form.formToArray();
			fields = $.arrayToObj(fields);
			$THIS = $(this);
			var isajax = true;
			
			if("0" == $THIS.attr("isajax")) isajax = false;
			if(!isajax){
				$form.ajaxSubmit({dataType:"html",success:function(html){
					$("#FORM-DIALOG").modal('hide');
						$("#TPL .tpl-title").text(' ');
						$("#TPL .content").html(html);
					}
				});
				return false;
			}
			$form.ajaxSubmit({dataType:"json",success:function(data){
				if(data.code==0){
					var o = $THIS.attr('o');
					if('add'==o){
						var row = [];
						$(".datatable th[col]").each(function(){
							row[row.length] = fields[$(this).attr('col')];
						});
						//添加按钮
						
						row[row.length] = '<button class="btn btn-small btn-primary edit" href="/OA/c?s=tpl&amp;o=form&amp;p=edit&amp;m_id=66&amp;pri=ds_id&amp;v=sys_ds&amp;key=34"><i class="icon-pencil"></i></button> '+
						'<button class="btn btn-small btn-danger delete" href="/OA/c?s=tpl&amp;o=delete&amp;isajax=1&amp;m_id=66&amp;pri=ds_id&amp;v=sys_ds&amp;key=34"><i class="icon-remove"></i></button>';
						debug(row);
						$(".datatable").dataTable().fnAddData(row);
						
					}else{
						
					}
					bootbox.alert("<p><i class='icon-ok'></i> 操作成功!</p>");
					//$form.resetForm();
					$("#FORM-DIALOG").modal('hide');
				}else{
					bootbox.alert("<p><i class='icon-remove'></i> "+data.msg+"</p>");
				}
			}});
			return false;
		});//*/
		
		btnDetail.live('click',function(){
			$.get($(this).attr("href"),function(data){
				//$target.html(data).show();
				bootbox.dialog({message:data,closeButton: true,show:true});
				return false;
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true,closeButton: true });
			});
			return false;
		});
	}
})(jQuery);
/**
 * 用于抽取数据库对象的脚本
 */
(function($){
	var $target = null;
	$.reflect = function(options){
		var opts = $.extend({}, $.reflect.defaults, options);
		$target = $("#"+opts['target']);
		init(opts);
	};
	$.reflect.defaults = {'target':'FORM-DIALOG'};
	function init(opts){
		$(opts['targets']).live('click',function(){
			//弹窗
			$.get($(this).attr("href"),function(data){
				$target.html(data).show();
				$target.modal({"backdrop"  : "static", "keyboard"  : true,show: true,  });
			});
		});
	}
})(jQuery);
	
/*
 * .wfdesign();
 * 关于工作流设计的脚本程序
 * */
(function($){
	var $target = $;
	var $panel = null;
	var $editForm = null;
	var $title_field = $obs_field = $remark_field = null;
	var startNodeFlag = false;
	var endNodeFlag = false;
	var startNode = endNode = processNode = arrowNode = null;
	var tpl_saved_flag = false;
	var tpl_id = undefined;
	var curNode = null;
	//核心函数
	$.fn.wfdesign = function(options){
		$target = this;
		startNodeFlag = false;
		endNodeFlag = false;
		tpl_saved_flag = false;
		var opts = $.extend({}, $.fn.slider.defaults, options); 
		tpl_id = opts['tpl_id'];
		if(tpl_id){
			startNodeFlag = true;
		}
		startNode = '<div class="wf-start"><i class="icon-play"></i></div>';
		endNode = '<div class="wf-end"><span><i class="icon-remove"></i></span><i class="icon-stop"></i></div>';
		processNode = '<div class="wf-node"><span><i class="icon-remove"></i></span><i class="icon-file-alt unset"></i><p class="unset">过程节点</p></div>';
		arrowNode = '<div class="wf-right"><i class="icon-arrow-right"></i></div>';
		$panel = $target.find(".panel");
		$editForm = $("#nodeEditForm");
		$title_field = $editForm.find("input[name='title']");
		$obs_field = $editForm.find("select[name='obs']");
		$remark_field = $editForm.find("textarea[name='remark']");
		init(opts);
	};
	//默认的配置信息
	$.fn.wfdesign.defaults = {    
		'target':'#TPL',
		'selector':"li > a"
	};
	function init(opts){
		//先删除关闭按钮
		$target.find(".nodes li:has(.wf-end)").remove();
		//启用拖拽功能
		$target.find(".items li" ).draggable({"helper":"clone"});
		//绑定拖放事件
		$panel.droppable({
			drop: function( event, ui ) {
				var $node = ui.helper;
				var $node_ul = $panel.find(".nodes");
				var cls = $node.find("div").attr("class");
				
				if(endNodeFlag){ bootbox.alert('该流程已经结束,不能继续添加!'); return;}
				if(!startNodeFlag){
					$node_ul.append($("<li></li>").html(startNode)).append($("<li>"+arrowNode+"</li>"));
					startNodeFlag = true;
				}
				switch(cls){
					case 'wf-node':
						$node_ul.append($("<li></li>").html(processNode));
					break;
					case 'wf-start':
						if(startNodeFlag) {bootbox.alert('该流程已添加了启动节点,无需继续添加!'); return;}
						startNodeFlag = true;
						$node_ul.append($("<li></li>").html(processNode));
					break;
					case 'wf-end':
						$node_ul.append($("<li></li>").html(endNode));
						endNodeFlag = true;
					return;
					
				}
				$node_ul.append($("<li>"+arrowNode+"</li>"));
			}
		});
		//绑定删除菜单
		$panel.find("li .wf-node span:has(i)").live('click',function(){
			curNode = $(this).parent().parent();
			bootbox.confirm("确定删除该节点么?", function(result) {
				if(!result) return;
				curNode.next().remove();
				curNode.remove();
				curNode = null;
			}); 
		});
		//绑定双击菜单
		$panel.find("li:has('.wf-node')").live('dblclick',function(){
			curNode = $(this);
			var flag = curNode.attr("flag");
			if(flag=='1'){
				//修改节点
				$title_field.val(curNode.attr("title"));
				$remark_field.val(curNode.attr("remark"));
				$obs_field.val(curNode.attr("obs"));
			}
			$editForm.modal("show");
		});
		//保存节点信息
		$editForm.find("form .btn-primary").click(function(){
			var title = $title_field.val();
			if(!title){
				bootbox.alert("标题不能为空!"); return;
			}
			var remark = $remark_field.val();
			var obs = $obs_field.val();
			curNode.find("p").text(title);
			curNode.attr("flag","1").attr("title",title).attr("obs",obs).attr("remark",remark);
			curNode.find("i,p").removeClass("unset").addClass("set");
			$editForm.modal('hide');
			$editForm.find("form").resetForm();
		});
		
		//保存节点的函数
		var saveNodes = function(id){
			var str = "";
			var index = 0;
			$panel.find(".nodes li[flag='1']").each(function(){
				str += "["+index+"]=n_title:"+$(this).attr("title")+"~"+
						"n_prev_code:"+(index++)+"~"+
	       				'n_cur_obs:'+$(this).attr("obs")+"~"+
	       				'n_code:'+(index)+"~"+
	       				'n_tpl:'+id+"~"+
	       				'n_remark:'+$(this).attr('remark')+"&";
			});
			str += "length="+index;
			str += "&isajax=1";
			debug(str);
			//保存节点信息
			var url = opts['url'];
			if(tpl_id ==undefined){
				url += "addNodes";
			}else{
				url += "editNodes";
				str += "&n_tpl="+tpl_id;
			}
			$.ajax({ "url": url, data:str, dataType:'json',type:'POST' })
				.done(function(data){
					debug(data);
					if(data.code==0){
						bootbox.alert("流程保存成功!");
					}else{
						bootbox.alert("流程节点存储异常!可能原因是:"+data.msg); return false;
					}
				});
		};
		
		
		//保存流程
		$("#form-tpl .btn-primary").click(function(){
			//之前的基本信息已保存
			if(tpl_saved_flag){
				saveNodes(tpl_id); return;
			}
			//判断有未编辑的节点
			if($panel.find(".nodes li:has('.unset')").length>0){
				bootbox.alert("您有节点尚未编辑,无法保存!"); return false;
			}
			//1.保存基本信息
			$("#form-tpl").ajaxSubmit(function(data){
				debug(data);
				if(data.code==0){
					tpl_saved_flag = true;
					if(tpl_id ==undefined){
						var id = data.data;
						saveNodes(id);
					}else{
						saveNodes(tpl_id);
					}
				}else{
					bootbox.alert("操作异常!原因可能是:"+data.msg); 
					return false;
				}
			});
			return false;
		});
	}
})(jQuery);
